package com.killer.edu.message.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.killer.edu.common.constant.MQConstant;
import com.killer.edu.common.mq.RocketMqService;
import com.killer.edu.common.mq.dto.BaseMqDTO;
import com.killer.edu.common.mq.listener.AbstractMqListener;
import com.killer.edu.common.util.ValidateUtils;
import com.killer.edu.course.api.dto.LessonDTO;
import com.killer.edu.message.api.dto.LessonStatusReleaseDTO;
import com.killer.edu.message.api.dto.Message;
import com.killer.edu.message.service.IMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.UUID;

@Slf4j
@Component
@RocketMQMessageListener(topic = MQConstant.Topic.LESSON_STATUS_RELEASE, consumerGroup = "${rocketmq.producer.group}" + "_" + MQConstant.Topic.LESSON_STATUS_RELEASE)
public class LessonStatusReleaseListener extends AbstractMqListener<BaseMqDTO> implements RocketMQListener<BaseMqDTO>{
	
    @Autowired
    private IMessageService messageService;
	@Autowired
    private RocketMqService rocketMqService;

    @Override
    public void onMessage(BaseMqDTO data) {
        log.info("onMessage-data:{}", JSON.toJSONString(data));
        ValidateUtils.notNullParam(data);
        ValidateUtils.notNullParam(data.getMessageId());
        //通过redis保存消费过的消息id，防止重复消费
        if (checkMessageId(data.getMessageId())) {
            return;
        }
        List<Integer> userIdList = messageService.saveMessage(Integer.parseInt(data.getData().toString()));
//        if (CollectionUtils.isNotEmpty(userIdList)) {
//            rocketMqService.convertAndSend(MQConstant.Topic.LESSON_RELEASE_SEND_MESSAGE, new BaseMqDTO<List<Integer>>(userIdList, UUID.randomUUID().toString()));
//        }
        if (CollectionUtils.isNotEmpty(userIdList)) {
            Message message = null;
            for (Integer userId : userIdList) {
                message=new Message();
                message.setUserId(userId);
                messageService.sendMessage(message);
            }
        }
        //记录该消息id已经消费过了
        this.updateMessageId(data.getMessageId());
    }
}